package com.primeton.wh.mcenter.impl.message.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.primeton.wh.mcenter.api.model.Message;
import com.primeton.wh.mcenter.impl.message.dao.MessageDAO;
import com.primeton.wh.mcenter.impl.message.service.IMessageService;
import com.primeton.wh.mcenter.impl.message.util.MessageConstants;
import com.primeton.wh.mcenter.impl.mqueue.productor.KafkaSender;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 消息表 服务实现类
 * </p>
 *
 * @author YunTao.Li
 * @since 2020-03-15
 */
@Service
public class MessageServiceImpl implements IMessageService {

    @Autowired
    private KafkaSender kafkaSender;
    @Autowired
    private MessageDAO messageDAO;

    private Gson gson = new GsonBuilder().create();

    /**
     * 消息查询（分页）
     *
     * @param condition :
     * @return : com.baomidou.mybatisplus.core.metadata.IPage<com.primeton.wh.mcenter.impl.message.entity.Message>
     * @author : YunTao.Li
     * @date : 2020/3/17 2020/3/17
     */
    public IPage<Message> getMessageList(Map<String, Object> condition) throws Throwable {
        IPage<Message> messageList = this.messageDAO.getMessageList(condition);
        return messageList;
    }

    /**
     * 消息查询（分页）
     *
     * @param condition :
     * @return : com.baomidou.mybatisplus.core.metadata.IPage<com.primeton.wh.mcenter.impl.message.entity.Message>
     * @author : jinyabin
     * @date : 2020-08-13
     */
    public IPage<Message> selectMessage(Map<String, Object> condition) throws Throwable {
        IPage<Message> messageList = this.messageDAO.selectMessage(condition);
        return messageList;
    }






    /**
     * 获得消息数量
     * condition参数:empCode,appCode
     *
     * @param condition :
     * @return : java.lang.Integer
     * @author : YunTao.Li
     * @date : 2020/5/7 2020/5/7
     */
    public Integer getUnReadMessageCount(Map<String, Object> condition) throws Throwable {
        Integer count = this.messageDAO.getUnReadMessageCount(condition);
        return count;
    }

    @Override
    public List<Message> getMessageListByApp(String appCode, String msgTo) throws Throwable {
        Map condition = new HashMap();
        condition.put("appCode", appCode);
        condition.put("msgTo", msgTo);
        return this.messageDAO.getMessageListWithOutPage(condition);
    }

    @Override
    public List<Message> getUnreadMessageListByApp(String appCode, String msgTo) throws Throwable {
        Map condition = new HashMap();
        condition.put("appCode", appCode);
        condition.put("mcStatus", 1);
        condition.put("msgTo", msgTo);
        return this.messageDAO.getMessageListWithOutPage(condition);
    }

    @Override
    public Message getMessageByApp(String appCode) throws Throwable {
        Map condition = new HashMap();
        condition.put("appCode", appCode);
        Message message = this.messageDAO.getMessageByCondition(condition);
        return null;
    }

    /**
     * 消息发送方法，用于把消息推送到队列中
     *
     * @param message :
     * @return : java.util.Map<java.lang.String,java.lang.String>
     * @author : YunTao.Li
     * @date : 2020/3/16 2020/3/16
     */
    @Override
    public Map<String, String> sendMesage(Message message) throws Throwable {
        Map<String, String> result = new HashMap<String, String>();
        result.put("code", "-1");

        try {

            // step1 : 補充必要信息
            String contentHtml = message.getMcContentHtml();
            if (StringUtils.isBlank(contentHtml)) {
                message.setMcContentHtml(message.getMcContent());
            }

            message.setMcStatus(MessageConstants.MESSAGE_STATUS_PREPUSH);
            message.setMcCreatetime(Calendar.getInstance().getTime());
            message.setMcSendTimes(1);

            /**
             * step2 : push message
             * 会根据type1短信；2邮件；3站内信来选择推送通道
             * 将MC_TO作为key来进行推送，确保按顺序消费
             * */
            String pushTopic = "topic1"; //TODO: 根据类型选择推送通道
            String key = message.getMcTo();

            kafkaSender.sendMessage(pushTopic, key, gson.toJson(message));
        } catch (Throwable e) {
            e.printStackTrace();
            throw e;
        }
        result.put("code", "1");
        return result;
    }

    /**
     * 新增消息记录(持久化方法临时方法)
     *
     * @param record :
     * @return : java.util.Map<java.lang.String,java.lang.String>
     * @author : YunTao.Li
     * @date : 2020/3/16 2020/3/16
     */
    @Override
    public Map<String, String> addMessage(Message record) throws Throwable {
        Map<String, String> result = new HashMap<String, String>();
        result.put("code", "-1");
        try {
            if (MessageConstants.MESSAGE_STATUS_EFFECTIVE != record.getMcStatus()) {
                record.setMcStatus(MessageConstants.MESSAGE_STATUS_PUSHED);
            }
            messageDAO.insertMessage(record);
        } catch (Throwable e) {
            e.printStackTrace();
            throw e;
        }

        result.put("code", "1");
        return result;
    }

    /**
     * 修改消息记录(持久化方法)
     *
     * @param record :
     * @return : java.util.Map<java.lang.String,java.lang.String>
     * @author : YunTao.Li
     * @date : 2020/3/16 2020/3/16
     */
    @Override
    public Map<String, String> editMessage(Message record) throws Throwable {
        Map<String, String> result = new HashMap<String, String>();
        result.put("code", "-1");
        try {
            messageDAO.updateMessage(record);
        } catch (Throwable e) {
            e.printStackTrace();
            throw e;
        }

        result.put("code", "1");
        return result;
    }

    /**
     * 待生效的消息扫描仪，将待生效的message变成已生效的
     *
     * @return : java.util.Map<java.lang.String,java.lang.String>
     * @author : YunTao.Li
     * @date : 2020/6/5 2020/6/5
     */
    @Override
    public Map<String, String> unEffectMessageScaner() throws Throwable {
        Map<String, String> result = new HashMap<String, String>();
        result.put("code", "-1");

        try {
            System.out.println("begin to scan");

            // step1 : 查出要修改的记录
            List<Message> expiredMessage = this.messageDAO.getExpiredMessages();

            System.out.println("expiredMessage count :" + expiredMessage.size());

            // step2 : 修改记录并保存
            for (Message message : expiredMessage) {
                message.setMcStatus(MessageConstants.MESSAGE_STATUS_PUSHED);
                this.editMessage(message);
            }
        } catch (Throwable e) {
            e.printStackTrace();
            throw e;
        }

        result.put("code", "1");
        return result;
    }
}
